import axios from 'axios'
import { Message } from 'element-ui'

import store from '../store'
import router from '../router'
// 基本配置
const config = {
  baseURL: '/api/v1',
  headers: {
    'content-type': 'application/json; charset=utf-8',
    accept: 'application/json',
  },
}
Object.assign(axios.defaults, config)

function handleError(error) {
  store.dispatch('LOADING', false)
  let { message, response } = error
  if (response) {
    const { data, status } = response
    if (data && data.message) {
      message = data.message
    }
    if (status === 401) {
      store.dispatch('LOGIN', { logout: false })
      router.push('/login')
    }
    // else if (status === 422) {
    //   message = typeof data.message === 'string' ? data.message : Array.isArray(data.message) ? data.message[0] : Object.values((data.message)[0])
    // } else if (status === 403) {
    //   message = data.message
    // }
  }
  Message.error(message)
  return Promise.reject(message)
}

axios.interceptors.request.use(
  config => {
    if (store.state.user.session) {
      config.headers.token = store.state.user.session
    }
    store.dispatch('LOADING', true)
    return config
  },
  console.error,
)

axios.interceptors.response.use(
  response => {
    store.dispatch('LOADING', false)
    return response
  },
  handleError,
)

export default axios
